import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_learning/utils/config.dart';

import 'ly_translate_model.dart';

class LYMSTranslateManager {
  LYMSTranslateManager._internal();
  static final LYMSTranslateManager _instance = LYMSTranslateManager._internal();
  static LYMSTranslateManager get share {
    return _instance;
  }

  final translateUrl = "https://api.cognitive.microsofttranslator.com/translate?api-version=3.0";

  Future<String?> translate({
    required String content,
    String? toLan,
    String? fromLan,
  }) async {
    final headerDict = {
      "Ocp-Apim-Subscription-Key": '',
      "Ocp-Apim-Subscription-Region": 'global',
      "Accept": "application/json",
      "Content-Type": "application/json;charset=UTF-8"
    };

    Options options = Options(headers: headerDict);
    final toCode = toLan ?? Config.lanCode;
    try {
      final response = await Dio().post("$translateUrl&to=$toCode", options: options, data: [
        {"Text": content}
      ]);
      debugPrint('$response');
      final jsonList = response.data as List?;
      if (jsonList != null && jsonList.isNotEmpty) {
        List<LYTranslateModel> result = [];
        for (final map in jsonList) {
          final model = LYTranslateModel.fromJson(map);
          result.add(model);
        }
        final model = result.length > 1
            ? result.reduce((value, element) {
                final vs = value.detectedLanguage?.score ?? 0;
                final es = element.detectedLanguage?.score ?? 0;
                return vs > es ? value : element;
              })
            : result.first;
        debugPrint('source：$content \n translate：${model.translations?.first.text}');
        return model.translations?.first.text;
      }
    } catch (e) {
      return null;
    }
    return null;
  }
}
